package cn.ydt.ydt.qrcode.service.Impl;

import cn.ydt.ydt.common.exception.YdtServiceException;
import cn.ydt.ydt.common.resful.JsonPage;
import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.common.utils.FileNameUtils;
import cn.ydt.ydt.pojo.community.model.QrCode;
import cn.ydt.ydt.qrcode.mapper.QrMapper;
import cn.ydt.ydt.qrcode.service.IQrService;
import cn.ydt.ydt.qrcode.utils.IDUtils;
import cn.ydt.ydt.qrcode.utils.QrUtils;
import cn.ydt.ydt.qrcode.utils.SecurityContextUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
@DubboService
public class QrService implements IQrService {
    @Autowired
    private QrMapper qrMapper;

    //    添加一个二维码
    @Override
    public void addNewQrCode() {
        QrCode qr = new QrCode();
        //
        long communityId = SecurityContextUtils.getNetCommunityId();
        QrCode qr2 = qrMapper.selectOneQr(communityId);
        log.info("communityID==={}",communityId);
        if(qr2!=null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST, "该社区二维码已存在！");
        }
        String qrName = IDUtils.generateUniqueId() + ".jpg";
        qr.setCommunityId(communityId);
        qr.setQrName(qrName);
        qrMapper.addQr(qr);
        String imagePath = "D:/fileUpload/ydt-file/" + qrName;
        String content ="/user/getUser/"+communityId;
        try {
            QrUtils.encodeimage(imagePath, "JPEG", content, 430, 430);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    查询单个二维码
    @Override
    public QrCode selectQr() {
        Long communityId = SecurityContextUtils.getNetCommunityId();
        log.info("二维码社区id{}",communityId);
        QrCode qr = qrMapper.selectOneQr(communityId);
        String qrName = qr.getQrName();
        qr.setQrName(FileNameUtils.filePath("/ydt-file/"+qrName));
        log.info("11111111111"+communityId);
        if (qr == null) {
            throw new YdtServiceException(StatusCode.BAD_REQUEST, "获取二维码失败，尝试访问的数据不存在！");
        }
        return qr;
    }

//    二维码列表
    @Override
    public JsonPage<QrCode> listByQr(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<QrCode> qr = qrMapper.list();
        if (qr == null) {
            throw new YdtServiceException(StatusCode.BAD_REQUEST, "服务器繁忙，请稍后再试！");
        }
        return JsonPage.restPage(new PageInfo<>(qr));
    }

}